;(function($){
	
	var TPL_ENTRY_COLLAPSED = new $.template('<div class="collapsed"><div class="entry-icons"><div class="item-star"></div></div><div class="entry-operations"><em><span class="operation-text">操作</span></em></div><div class="entry-main">&nbsp;<div class="entry-secondary"><span class="entry-title">{name}</span>&nbsp;<span class="entry-secondary-snippet">-&nbsp;{description}</span></div></div></div>');
	var TPL_ENTRY_CONTAINER = new $.template('<div class="entry-container"></div>');
	
	var TPL_ENTRY_DETAILS = null;
	var TPL_ENTRY_RESOURCE = new $.template('<div></div>');
	
	function Entry(playlist, index){
		this.id = playlist.id;
		this.playlist = playlist;
		this.index = index;
		this.entryEl = $('<div class="entry"></div>');
		this.collapsed = true;
		var data = {
			'name' : this.getName(),
			'description' : this.getDescription(),
			'tags' : this.getTagsAsString(),
			'creator' : this.playlist.owner.username
		};
		
		this.collapsedEl = $(TPL_ENTRY_COLLAPSED.applyTemplate(data));
		this.containerEl = $(TPL_ENTRY_CONTAINER.applyTemplate(data));
		
	    this.collapsedEl.appendTo(this.entryEl);
	    //靠CSS来控制是否显示
		this.containerEl.appendTo(this.entryEl);
		$(TPL_ENTRY_DETAILS.applyTemplate(data)).appendTo(this.containerEl);   //details
		
		this.collapsedEl.click(this.collapsedClicked.bind(this));
		
		this.operationMenu();
	}
	
	$.extend(Entry.prototype, {
		
		getName : function(){
			if(this.name){
				return this.name;
			}
			var n = this.playlist.name;
			if(!n){
				n = '未知标题';
			}
			this.name = n;
			return n;
		},
		
		getDescription : function(){
			if(this.description){
				return this.description;
			}
			var d = this.playlist.description;
			if(!d){
				d = '';
			}
			this.description = d;
			return d;
		},
		
		expand : function(){
			if(!!this.collapsed){
				this.entryEl.addClass('expanded');
				this.collapsed = false;
			}
		},
		
		collapse : function(){
			if(!this.collapsed){
				this.entryEl.removeClass('expanded');
				this.collapsed = true;
			}
		},
		
		collapsedClicked : function(){
			$().trigger('entrysetcurrent', [this.id]);
			if(!!this.collapsed){
				this.expand();
			}else{
				this.collapse();
			}
		},
		
		setCurrent : function(){
			if(!this.current){
				this.entryEl.attr('id', 'current-entry');
				this.current = true;
			}
		},
		
		removeCurrent : function(){
			if(!!this.current){
				this.entryEl.removeAttr('id');
				this.current = false;
				this.collapse();
			}
		},
		
		remove : function(){
			//$.event.trigger('entryremove', [this.id], $('#center_content_container'));
			$().trigger('entryremove', [this.id]);
		},
		
		addResource : function(){
			var self = this;
			var $form = $('#addPlaylistResForm');
        	$form.clearForm().resetForm().dialog({title:'添加标签资源'});
        	$('input:first', $form).trigger('focus');
        	//设置playlistId
        	$('input[@name=playlistId]', $form).val(this.id);
        	//focus on the first input element
        	$('.actions>a', $form).bind('click', function(e){
        		$form.dialogClose();
        		return false;
        	});
        	var options = {
      			beforeSubmit: function(formArray, jqForm, options) {
      				//do something before submit form
      				$.ui.indicator.show();
      			},
      			dataType : 'json',
      			success : function(data){
      				$.ui.indicator.hide();
      				self.doAddResource(data);
      				$form.dialogClose();
      			}
  			};
  			$form.validate({
  				submitHandler: function(form) {
					$(form).ajaxSubmit(options);
				}
  			});
		},
		
		doAddResource : function(data){
			
		},
		
		addComment : function(){
			var self = this;
			var $form = $('#addPlaylistCommentForm');
        	$form.clearForm().resetForm().dialog({title:'添加评论'});
        	//focus on the first input element
        	$('input:first', $form).trigger('focus');
        	//设置playlistId
        	$('input[@name=playlistId]', $form).val(this.id);
        	$('.actions>a', $form).bind('click', function(e){
        		$form.dialogClose();
        		return false;
        	});
        	var options = {
      			beforeSubmit: function(formArray, jqForm, options) {
      				//do something before submit form
      				$.ui.indicator.show();
      			},
      			dataType : 'json',
      			success : function(data){
      				$.ui.indicator.hide();
      				self.doAddComment(data);
      				$form.dialogClose();
      			}
  			};
  			$form.validate({
  				submitHandler: function(form) {
					$(form).ajaxSubmit(options);
				}
  			});
		},
		
		doAddComment : function(data){
			
		},
		
		getTagsAsString : function(){
			var tagString = [];
			$.each(this.playlist.tags, function(i, tag){
				tagString.push(!!tag.name ? tag.name : '');
			});
			return tagString.join(',');
		},
		
		operationMenu : function(){
			var self = this;
			$('em', this.entryEl).click(function(e){
				e.stopPropagation();
				$(this).menu({
					parentEl : $('#playlist-box'),
					items : [
						{
							'text' : '编缉',
							'handler' : function(){}
						},
						{
							'text' : '删除',
							'handler' : function(){self.remove();}
						}, '-',
						{
							'text' : '添加资源',
							'handler' : function(){self.addResource();}
						},
						{
							'text' : '添加评论',
							'handler' : function(){self.addComment();}
						},
						{
							'text' : '编缉标签',
							'handler' : function(){}
						}, '-',
						{
							'text' : '设置权限',
							'handler' : function(){}
						}
					]
				});
			});
		}
	});
	
	$.sharetime = $.sharetime || {};
	
	$.sharetime.playlist = (function(){
		var HTML_ENTRIES_CONTAINER = '<div style="padding:8px;"><h2 class="simple">全部书签列表</h2><div id="playlist-box"><div id="entries" class="list"></div></div></div>';
		
		var _entries = [], _entryMap = {};
		
        function _init(){
        	$.ui.indicator.show();
        	$.ajax({
        		type : "GET",
        		url : "/view/viewmyplaylist",
        		async : false, //sync request
        		dataType : "json",
        		success : function(data){
        			$.ui.indicator.hide();
        			if(data.msg == 'OK'){
        				var playlists = data.playlists;
        				$("#center_content_container").html(HTML_ENTRIES_CONTAINER);
        				if(playlists.length == 0){
        					_showNoEntriesMsg();
        					return;
        				}
        				$.each(playlists, function(i, pl){
        					var entry = new Entry(pl, i);
							_addEntry(entry);      					
        				});
        			}
        		}
        	});
        }
        
        function _ajaxSetup(){
        	//global ajax setup
        		$.ajaxSetup({
					timeout : 15*1000,
					cache : false,
					error : function(xhr, msg, e){
						$.ui.indicator.hide();
						throw e;
					}
        		});
        }
        
        function _initBindEvent(){
        	$('#addPlaylistBox').makeDraggable();
        	$().bind('entryadd', _addEntry);
        	$().bind('entryremove', function(e, id){
        			_removeEntry(id)
        		});
        	$().bind('entrysetcurrent', function(e, id){
        			_setCurrentEntry(id);
        		});
        }
        
        function _initTemplates(){
        	TPL_ENTRY_DETAILS = new $.template($('#playlistDetail').val());
        }
        
        function _setSize(){
			
		}
        
        function _showNoEntriesMsg(){
        	$('<div id="no-entries-msg">当前没有书签书签列表，<a href="#" onclick="return false;">添加</a>一个</div>').appendTo($('#entries'));
        }
        
        function _doAddPlaylist(data){
        	var pl = data.playlist;
        	var entry = new Entry(pl, _entries.length);
      		_addEntry(entry);
        }
        
        function _addEntry(entry){
        	_entries.push(entry);
        	_entryMap[entry.id] = entry;
        	if(_entries.length == 1){
      			$("#entries").empty().append(entry.entryEl);			
      		}else{
      			$("#entries").append(entry.entryEl);
      		}
        }
        
        function _removeEntry(id){
        	var entry = _entryMap[id];
        	if(!entry){
        		return;
        	}
        	if(!confirm('确定要删除吗')){
        		return;
        	}
        	$.ui.indicator.show();
        	$.ajax({
        		type : 'POST',
        		url : 'editplaylist',
        		data : {'id' : entry.id, '_method' : 'DELETE'},
        		dataType : 'json',
        		success : function(data){
        			$.ui.indicator.hide();
        			_entries.remove(entry);
        			delete _entryMap[entry.id];
      				entry.entryEl.remove();
      				if(_entries.length == 0){
      					_showNoEntriesMsg();
      				}
        		}
        	});
        }
        
        function _setCurrentEntry(id){
        	$.each(_entries, function(i, entry){
        		if(entry.id != id){
        			entry.removeCurrent();
        		}
        	});
        	var curEntry = _entryMap[id];
        	if(!!curEntry){
        		curEntry.setCurrent();
        	}
        }
        
        return {
        	init : function(){
        		_ajaxSetup();
        		_initBindEvent();
        		_initTemplates();
        		_init();
        	},
        	
        	showAddPlaylistDlg : function(entry){
        		var $form = $('#addPlaylistForm');
        		//打开对话框
        		$form.clearForm().resetForm().dialog({title:'添加书签列表'});
        		//focus on the first input element
        		$('input:first', $form).trigger('focus');
        		$('.actions>a', $form).bind('click', function(e){
        			$form.dialogClose();
        			return false;
        		});
        		var options = {
      				beforeSubmit: function(formArray, jqForm, options) {
      					//do something before submit form
      					$.ui.indicator.show();
      				},
      				dataType : 'json',
      				success : function(data){
      					$.ui.indicator.hide();
      					_doAddPlaylist(data);
      					$form.dialogClose();
      				}
  				};
  				$form.validate({
  					submitHandler: function(form) {
						$(form).ajaxSubmit(options);
					}
  				});
        		return false;
        	},
 
        	editPlaylist : function(id){
        		
        	}
        }
        	
	})();
	
})(jQuery);